package com.hegongda.okcmall.product.service.impl;

import com.hegongda.okcmall.product.entity.AttrAttrgroupRelationEntity;
import com.hegongda.okcmall.product.entity.AttrGroupEntity;
import com.hegongda.okcmall.product.entity.CategoryEntity;
import com.hegongda.okcmall.product.service.AttrAttrgroupRelationService;
import com.hegongda.okcmall.product.service.AttrGroupService;
import com.hegongda.okcmall.product.vo.AttrRespVo;
import com.hegongda.okcmall.product.vo.AttrVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hegongda.common.utils.PageUtils;
import com.hegongda.common.utils.Query;

import com.hegongda.okcmall.product.dao.AttrDao;
import com.hegongda.okcmall.product.entity.AttrEntity;
import com.hegongda.okcmall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;

    @Autowired
    private CategoryServiceImpl categoryService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        // 先保存基本属性信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        baseMapper.insert(attrEntity);

        // 保存属性与分组的关联信息(销售属性可以不用设置分组信息)
        if (attr.getAttrType() == 1) {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            entity.setAttrGroupId(attr.getAttrGroupId());
            entity.setAttrId(attrEntity.getAttrId());
            attrgroupRelationService.save(entity);
        }
    }

    @Override
    public PageUtils queryAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        int type = "base".equalsIgnoreCase(attrType) ? 1 : 0;
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", type);
        if (catelogId.longValue() != 0){
            // 不是查询全部
            queryWrapper.eq("catelog_id", catelogId );
        }
        // 获取查询条件
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = (List<AttrEntity>) pageUtils.getList();
        // 进行查询分类名和分组名
        List<AttrRespVo> collectList = list.stream().map((attr) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);
            AttrAttrgroupRelationEntity entity = attrgroupRelationService.selectOne(attr.getAttrId());
            if (entity != null) {
                AttrGroupEntity groupEntity = attrGroupService.selectOne(entity.getAttrGroupId());
                // 设置分组名
                attrRespVo.setGroupName(groupEntity.getAttrGroupName());
            }
            // 查询分类名并进行设置
            CategoryEntity categoryEntity = categoryService.selectOne(attr.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collectList);
        return pageUtils;
    }

    /**
     *  修改时进行回显相关的信息
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        // 先查attr
        AttrEntity attrEntity = baseMapper.selectOne(new QueryWrapper<AttrEntity>().eq("attr_id", attrId));
        BeanUtils.copyProperties(attrEntity, attrRespVo);

        // 查找groupId 与 groupName 并进行设置
        AttrAttrgroupRelationEntity entity = attrgroupRelationService.selectOne(attrId);
        if (entity != null){
            attrRespVo.setAttrGroupId(entity.getAttrGroupId());
            AttrGroupEntity groupEntity = attrGroupService.selectOne(entity.getAttrGroupId());
            if (groupEntity != null){
                attrRespVo.setGroupName(groupEntity.getAttrGroupName());
            }
        }

        // 查找categoryPath
        Long[] categoryPath = categoryService.getCategoryPath(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(categoryPath);
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrRespVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 跟新attr
        baseMapper.updateById(attrEntity);
        // 更新中间表(销售属性无需更新中间表)
        if (attr.getAttrType() == 1) {
            AttrAttrgroupRelationEntity entity = attrgroupRelationService.selectOne(attr.getAttrId());
            if (entity == null) {
                // 说明原来就没有进行分组设置，需要进行插入
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrgroupRelationService.save(attrAttrgroupRelationEntity);
            } else {
                // 进行更新操作
                entity.setAttrGroupId(attr.getAttrGroupId());
                attrgroupRelationService.updateById(entity);
            }
        }
    }

    @Override
    public PageUtils queryNOAttrPage(Map<String, Object> params, Long catelogId, int i, Long groupId) {
        // 获取当前分类下的其他分组
        List<AttrGroupEntity> groupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>()
                .eq("catelog_id", catelogId)
                .ne("attr_group_id", groupId));
        List<Long> groupIdList = groupEntities.stream().map((entity) -> entity.getAttrGroupId()).collect(Collectors.toList());
        // 获取其他分组下已经关联的属性
        List<AttrAttrgroupRelationEntity> relationEntities = null;
        if (groupIdList != null && groupIdList.size() > 0) {
             relationEntities = attrgroupRelationService.list(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdList));
        }
        List<Long> attrIds = relationEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id", catelogId).eq("attr_type", i);
        if (attrIds != null && attrIds.size() > 0){
            queryWrapper.notIn("attr_id", attrIds);
        }
        // 获取当前
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = (List<AttrEntity>) pageUtils.getList();
        List<AttrEntity> collect = list.stream().filter(attrEntity -> {
            int count = attrgroupRelationService.count(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId())
                    .eq("attr_group_id", groupId));
            return count <= 0;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrEntity selectOne(Long attrId) {
        return baseMapper.selectById(attrId);
    }

}